package com.wxl.common.util

import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import android.view.inputmethod.InputMethodManager

/**
 * create file time : 2021/3/18
 * create user : wxl
 * subscribe :
 */
class KeyBoardUtil {

    companion object {

        private var rootViewVisibleHeight: Int = 0 //纪录根视图的显示高度
        private var listener: ViewTreeObserver.OnGlobalLayoutListener? = null

         interface OnKeyBoardStateChangeListener {
            fun onKeyBoardStateChanged(isShow: Boolean, height: Int)
        }

        fun onObserverKeyBoardStateChange(act: Activity, l: OnKeyBoardStateChangeListener?) {
            listener = ViewTreeObserver.OnGlobalLayoutListener {
                //获取当前根视图在屏幕上显示的大小
                val r = Rect()
                act.window.decorView.getWindowVisibleDisplayFrame(r)
                val visibleHeight = r.height()
                if (rootViewVisibleHeight == 0) {
                    rootViewVisibleHeight = visibleHeight
                    return@OnGlobalLayoutListener
                }

                //根视图显示高度没有变化，可以看作软键盘显示／隐藏状态没有改变
                if (rootViewVisibleHeight == visibleHeight) {
                    return@OnGlobalLayoutListener
                }

                //根视图显示高度变小超过200，可以看作软键盘显示了
                if (rootViewVisibleHeight - visibleHeight > 200) {
                    l?.onKeyBoardStateChanged(true, rootViewVisibleHeight - visibleHeight)
                    rootViewVisibleHeight = visibleHeight
                    return@OnGlobalLayoutListener
                }

                //根视图显示高度变大超过200，可以看作软键盘隐藏了
                if (visibleHeight - rootViewVisibleHeight > 200) {
                    l?.onKeyBoardStateChanged(false,visibleHeight - rootViewVisibleHeight)
                    rootViewVisibleHeight = visibleHeight
                    return@OnGlobalLayoutListener
                }

            }
            act.window.decorView.viewTreeObserver.addOnGlobalLayoutListener(listener)
        }


        fun releaseObserver(act: Activity){
            listener?:return
            act.window.decorView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }

        fun showSoftInput(view: View?) {
            if (view == null) return
            val inputMethodManager = view.context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager?.showSoftInput(view, 0)
        }

        fun hideSoftInput(view: View?) {
            if (view == null) return
            val inputMethodManager = view.context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager?.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }
}